package dto

import (
	"strings"

	"gorm.io/gorm"

	"ssdevice/common/utils"
)

type OrderBy struct {
	SortOrder string `form:"sortOrder" search:"-"`
	SortField string `form:"sortField" search:"-"`
}

const (
	ORDER_DESC = "DESC"
	ORDER_ASC  = "ASC"
)

func OrderDest(sort string, bl bool, sortInfo ...OrderBy) func(db *gorm.DB) *gorm.DB {
	if len(sortInfo) == 0 || len(sortInfo[0].SortField) == 0 || len(sortInfo[0].SortOrder) == 0 {
		return func(db *gorm.DB) *gorm.DB {
			//return db.Order(clause.OrderByColumn{Column: clause.Column{Name: sort}, Desc: bl})
			sort = strings.ReplaceAll(sort, " ", "")
			sort = strings.ReplaceAll(sort, ",", `","`)
			return db.Order(`"` + sort + `"` + utils.If(bl, " DESC NULLS LAST", " NULLS LAST").(string))
		}
	}
	sortField := sortInfo[0].SortField
	sortOrder := sortInfo[0].SortOrder
	return OrderByCust(sortField, sortOrder)
}

func OrderByCust(sort string, by string) func(db *gorm.DB) *gorm.DB {
	//驼峰字段转数据库字段：userName ->  user_name
	sort = utils.CamelCaseToUdnderscore(sort)

	//排序方式
	desc := utils.If(strings.ToUpper(by) != ORDER_ASC, true, false).(bool)
	return func(db *gorm.DB) *gorm.DB {
		//return db.Order(clause.OrderByColumn{Column: clause.Column{Name: sort}, Desc: desc})
		return db.Order(`"` + sort + `"` + utils.If(desc, " DESC NULLS LAST", " NULLS LAST").(string))
	}
}
